package com.lb.shopguide.ui.fragment.boss.market;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.BuildConfig;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.event.boss.AdviceRefreshEvent;
import com.lb.shopguide.event.jump.JumpMyActivityFromMarketEvent;
import com.lb.shopguide.event.jump.JumpMyActivityFromSecretaryEvent;
import com.lb.shopguide.event.jump.JumpSecretaryEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.manager.interf.WebviewInterface;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.fragment.boss.FragmentBossHome;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;

/**
 * webview页面，全部由h5完成
 */
public class FragmentUseTemplate extends BaseCommonFragment implements WebviewInterface {
    @BindView(R.id.webview)
    BridgeWebView mWebView;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    private String templateCode;
    private String templateName;
    private String storeCode;
    private String msgId;

    private StringBuffer url;

    public static FragmentUseTemplate newInstance(String templateCode, String templateName, String storeCode, String msgId) {
        FragmentUseTemplate fragmentUseTemplate = new FragmentUseTemplate();
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(storeCode)) {
            bundle.putString(AppConstant.STORE_CODE, storeCode);
        }
        if (!TextUtils.isEmpty(templateCode)) {
            bundle.putString(AppConstant.TEMPLATE_CODE, templateCode);
        }
        if (!TextUtils.isEmpty(templateName)) {
            bundle.putString(AppConstant.TEMPLATE_NAME, templateName);
        }
        if (!TextUtils.isEmpty(msgId)) {
            bundle.putString(AppConstant.MSG_ID, msgId);
        }
        fragmentUseTemplate.setArguments(bundle);
        return fragmentUseTemplate;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_use_template;
    }

    @Override
    public void initData() {
        url = new StringBuffer();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.STORE_CODE)) {
            storeCode = bundle.getString(AppConstant.STORE_CODE);
        }
        if (bundle.containsKey(AppConstant.TEMPLATE_CODE)) {
            templateCode = bundle.getString(AppConstant.TEMPLATE_CODE);
        }
        if (bundle.containsKey(AppConstant.TEMPLATE_NAME)) {
            templateName = bundle.getString(AppConstant.TEMPLATE_NAME);
        }
        if (bundle.containsKey(AppConstant.MSG_ID)) {
            msgId = bundle.getString(AppConstant.MSG_ID);
        }
        prepareUrl();
        if (!TextUtils.isEmpty(msgId)) {
            sendRequestReadAdvices(msgId);
        }
    }

    private void prepareUrl() {
        if (BuildConfig.DEBUG) {
            url.append("https://sintest.storeer.com/boss/sell_template?");
            if (!TextUtils.isEmpty(templateCode)) {
                url.append("templateCode=" + templateCode + "&");
            }
            if (!TextUtils.isEmpty(templateName)) {
                try {
                    templateName = URLEncoder.encode(templateName, "UTF-8");
                    url.append("templateName=" + templateName + "&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (!TextUtils.isEmpty(storeCode)) {
                url.append("storeCode=" + storeCode + "&");
            }
            if (!TextUtils.isEmpty(msgId)) {
                url.append("msgId=" + msgId + "&");
            }
//            String userToken = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJ1c2VyQ29kZSI6ImU3NzhmODBiYzFjYjRlMDliNDA5NWNmMDNiZTcwOWY3IiwiaXNzIjoid2x3YkFwaSIsImF1ZCI6IjdhMTRlNzAxNWQwYTQ5YzZhMzA4Yjk4ZTQwMGYyOWQ4In0.ft6mA5Pg65e8Eayv_KKfECF6RSIp55TJdJJEfo9lSDuxEgNZxWZRPZ6YK0hW4zusZ7a6Nz09gs2VrqzW7CjZcQ";
            url.append("token=" + UserConfigManager.getInstance(GuideApplication.context()).getUserToken() + "&type=android");
//            url.append("token=" + userToken + "&type=android");
        }
    }

    @Override
    public void initView() {
// 进度条控制
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (isVisible()) {
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    super.onProgressChanged(view, newProgress);
                }
            }

        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLightTouchEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setDefaultHandler(new DefaultHandler());
        mWebView.loadUrl(url.toString());

        goToMyActivity();
        backToHome();
        backToPrePage();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentUseTemplate.class.getName();
    }

    private void sendRequestReadAdvices(String msgId) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    EventBus.getDefault().post(new AdviceRefreshEvent());
                }
            }
        };
        ApiMethodBoss.readActivitySuggestion(new SimpleLbObserver(listener, otherListener), msgId, this, FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public void share() {

    }

    @Override
    public void getBarcode() {

    }

    @Override
    public void call() {

    }

    @Override
    public void savePic() {

    }

    @Override
    public void charge() {

    }

    @Override
    public void backToActivityList() {

    }

    @Override
    public void goToMyActivity() {
        mWebView.registerHandler("goToMyActivity", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                FragmentMarketing fragmentMarketing = findFragment(FragmentMarketing.class);
                if (fragmentMarketing == null) {
                    popTo(FragmentBossHome.class, false, new Runnable() {
                        @Override
                        public void run() {
                            EventBus.getDefault().post(new JumpMyActivityFromSecretaryEvent());
                        }
                    });
                } else {
                    popTo(FragmentMarketing.class, false, new Runnable() {
                        @Override
                        public void run() {
                            EventBus.getDefault().post(new JumpMyActivityFromMarketEvent());
                        }
                    });
                }
            }
        });
    }

    @Override
    public void backToHome() {
        mWebView.registerHandler("backToHome", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                popTo(FragmentBossHome.class, false, new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new JumpSecretaryEvent());
                    }
                });
            }
        });
    }

    @Override
    public void backToPrePage() {
        mWebView.registerHandler("backToPrePage", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                pop();
            }
        });
    }
}
